package com.simon.jkxj

import android.app.DatePickerDialog
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.simon.jkxj.databinding.ActivityCompleteProfileBinding
import com.simon.jkxj.model.AppDatabase
import com.simon.jkxj.model.User
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.*

class CompleteProfileActivity : AppCompatActivity() {
    private lateinit var binding: ActivityCompleteProfileBinding
    private var userId: Int = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityCompleteProfileBinding.inflate(layoutInflater)
        setContentView(binding.root)

        userId = intent.getIntExtra("userId", 0)
        Log.d("ProfileDebug", "Received userId: $userId")
        setupGenderSpinner()
        setupConstitutionSpinner()
        setupBirthdayPicker()
        setupClickListeners()
        loadExistingUserInfo()

        binding.ivBack.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
    }

    private fun loadExistingUserInfo() {
        if (userId != 0) {
            lifecycleScope.launch {
                val userDao = AppDatabase.getDatabase(this@CompleteProfileActivity).userDao()
                val user = withContext(Dispatchers.IO) { userDao.getUserById(userId) }
                withContext(Dispatchers.Main) {
                    user?.let {
                        Log.d("ProfileDebug", "User retrieved: ID=${it.id}, Username=${it.username}, Gender=${it.gender}")
                        binding.tvDisplayUsername.text = "尊敬的 ${it.username}:"

                        binding.spinnerGender.setSelection(
                            when (it.gender) {
                                "男" -> 0
                                "女" -> 1
                                "保密" -> 2
                                else -> 2 // 默认保密
                            }
                        )
                        binding.etBirthday.setText(it.birthday)
                        binding.etHeight.setText(it.height?.toString())
                        binding.etWeight.setText(it.weight?.toString())
                        binding.spinnerConstitution.setSelection(
                            when (it.constitution) {
                                "平和体质" -> 0
                                "气虚体质" -> 1
                                "阳虚体质" -> 2
                                "阴虚体质" -> 3
                                "痰湿体质" -> 4
                                "湿热体质" -> 5
                                "血瘀体质" -> 6
                                "气郁体质" -> 7
                                "特禀体质" -> 8
                                "未测" -> 9
                                else -> 9 // 默认未测
                            }
                        )
                    } ?: run {
                        Log.e("ProfileDebug", "User with ID $userId not found in database.")
                    }
                }
            }
        } else {
            Log.e("ProfileDebug", "userId is 0, cannot load user info.")
        }
    }

    private fun setupGenderSpinner() {
        val genders = listOf("男", "女", "保密")
        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, genders)
        binding.spinnerGender.adapter = adapter
    }

    private fun setupConstitutionSpinner() {
        val types = listOf("平和体质", "气虚体质", "阳虚体质", "阴虚体质", "痰湿体质", "湿热体质", "血瘀体质", "气郁体质", "特禀体质", "未测")
        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, types)
        binding.spinnerConstitution.adapter = adapter
    }

    private fun setupBirthdayPicker() {
        binding.etBirthday.setOnClickListener {
            val c = Calendar.getInstance()
            val dialog = DatePickerDialog(this, { _, year, month, day ->
                binding.etBirthday.setText("$year-${month+1}-$day")
            }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH))
            dialog.show()
        }
    }

    private fun setupClickListeners() {
        binding.btnSave.setOnClickListener {
            val gender = binding.spinnerGender.selectedItem.toString()
            val birthday = binding.etBirthday.text.toString()
            val height = binding.etHeight.text.toString().toFloatOrNull()
            val weight = binding.etWeight.text.toString().toFloatOrNull()
            val constitution = binding.spinnerConstitution.selectedItem.toString()

            if (gender == "保密" || gender.isEmpty()) {
                Toast.makeText(this, "请选择您的性别", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            lifecycleScope.launch {
                val userDao = AppDatabase.getDatabase(this@CompleteProfileActivity).userDao()
                withContext(Dispatchers.IO) {
                    val user = userDao.getUserById(userId)
                    if (user != null) {
                        val updated = user.copy(
                            gender = gender,
                            birthday = birthday,
                            height = height,
                            weight = weight,
                            constitution = constitution
                        )
                        userDao.updateUser(updated)
                    }
                }
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@CompleteProfileActivity, "信息完善成功", Toast.LENGTH_SHORT).show()
                    val intent = Intent(this@CompleteProfileActivity, MainActivity::class.java)
                    startActivity(intent)
                    finish()
                }
            }
        }

        binding.btnSkip.setOnClickListener {
            val intent = Intent(this@CompleteProfileActivity, MainActivity::class.java)
            startActivity(intent)
            finish()
        }
    }
} 